package cn.com.chec.en.controller.admin;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.com.chec.en.dao.ChannelInfoDao;
import cn.com.chec.en.dao.FlashInfoDao;
import cn.com.chec.en.dao.LanguageInfoDao;
import cn.com.chec.en.model.domain.ChannelInfo;
import cn.com.chec.en.model.domain.FlashInfo;
import cn.com.chec.en.model.domain.LanguageInfo;
import cn.com.chec.en.util.FileUtils;
import cn.com.chec.en.util.PageBean;

@Controller
@RequestMapping({ "/admin/flash" })
public class FlashInfoAdminController {
	protected static final Logger logger = Logger
			.getLogger(FlashInfoAdminController.class);

	@Resource
	private ChannelInfoDao channelInfoDao;

	@Resource
	private LanguageInfoDao languageInfoDao;

	@Resource
	private FlashInfoDao flashInfoDao;

	@Resource
	private List<String> allowedUploadFlash;

	@SuppressWarnings("unchecked")
	@RequestMapping({ "/showInsert" })
	public ModelAndView showInsert(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/flashInfo/flashInfoOpr");
		int languageId = StringUtils.isNotBlank(request
				.getParameter("languageId")) ? Integer.parseInt(request
				.getParameter("languageId")) : 1;
		int channelId = StringUtils.isNotBlank(request
				.getParameter("channelId")) ? Integer.parseInt(request
				.getParameter("channelId")) : 0;
		List<LanguageInfo> languageInfoList = this.languageInfoDao.getAll();
		List<ChannelInfo> channelInfoList = this.channelInfoDao
				.getSubListByParentIdLanguageId(0, 0, 0, 2147483647);
		map.put("languageInfoList", languageInfoList);
		map.put("channelInfoList", channelInfoList);
		map.put("languageId", Integer.valueOf(languageId));
		map.put("channelId", Integer.valueOf(channelId));
		map.put("userRightsSession",
				(List<String>) session.getAttribute("systemUserRigthList"));
		map.put("act", "insert");
		mav.addAllObjects(map);
		return mav;
	}

	@SuppressWarnings("deprecation")
	@RequestMapping({ "/insert" })
	public ModelAndView insert(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/common/message");
		String message = "";

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("flashFile");
		String originalFilename = multipartFile.getOriginalFilename();
		if (!isAllowed(originalFilename)) {
			map.put("message", "上传文件类型不符合,必须是以下几种<br/>"
					+ this.allowedUploadFlash.toString());
			return new ModelAndView("admin/common/message", map);
		}

		String fileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")
				+ "." + FilenameUtils.getExtension(originalFilename);
		String basePath = request.getRealPath("/") + "/";
		String relativePath = "userfiles/upload/flash/"
				+ DateFormatUtils.format(new Date(), "yyyy-MM-dd").replaceAll(
						"-", "/") + "/";
		FileUtils.mkdirs(basePath + relativePath);
		multipartFile.transferTo(new File(basePath + relativePath + fileName));

		int languageId = StringUtils.isNotBlank(request
				.getParameter("languageId")) ? Integer.parseInt(request
				.getParameter("languageId")) : 1;
		int channelId = StringUtils.isNotBlank(request
				.getParameter("channelId")) ? Integer.parseInt(request
				.getParameter("channelId")) : 0;
		String flashName = request.getParameter("flashName");
		FlashInfo info = new FlashInfo();
		info.setLanguageId(languageId);
		info.setChannelId(channelId);
		info.setFlashName(flashName);
		info.setFlashPath(relativePath + fileName);

		if (this.flashInfoDao.insert(info))
			message = "添加Flash成功!";
		else {
			message = "添加Flash失败!";
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping({ "/showUpdate" })
	public ModelAndView showUpdate(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/flashInfo/flashInfoOpr");
		int flashId = StringUtils.isNotBlank(request.getParameter("flashId")) ? Integer
				.parseInt(request.getParameter("flashId")) : 0;
		List<LanguageInfo> languageInfoList = this.languageInfoDao.getAll();
		List<ChannelInfo> channelInfoList = this.channelInfoDao
				.getSubListByParentIdLanguageId(0, 0, 0, 2147483647);
		FlashInfo flashInfo = this.flashInfoDao.getFlashByFlashId(flashId);
		map.put("channelInfoList", channelInfoList);
		map.put("languageInfoList", languageInfoList);
		map.put("flashInfo", flashInfo);
		map.put("userRightsSession",
				(List<String>) session.getAttribute("systemUserRigthList"));
		map.put("act", "update");
		mav.addAllObjects(map);
		return mav;
	}

	@SuppressWarnings("deprecation")
	@RequestMapping({ "/update" })
	public ModelAndView update(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/common/message");
		String message = "";
		int flashId = StringUtils.isNotBlank(request.getParameter("flashId")) ? Integer
				.parseInt(request.getParameter("flashId")) : 0;
		int languageId = StringUtils.isNotBlank(request
				.getParameter("languageId")) ? Integer.parseInt(request
				.getParameter("languageId")) : 1;
		int channelId = StringUtils.isNotBlank(request
				.getParameter("channelId")) ? Integer.parseInt(request
				.getParameter("channelId")) : 0;
		String flashName = request.getParameter("flashName");

		FlashInfo flashInfo = new FlashInfo();
		flashInfo.setFlashId(flashId);
		flashInfo.setLanguageId(languageId);
		flashInfo.setChannelId(channelId);
		flashInfo.setFlashName(flashName);

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("flashFile");
		String originalFilename = multipartFile.getOriginalFilename();
		if (StringUtils.isNotBlank(originalFilename)) {
			if (!isAllowed(originalFilename)) {
				map.put("message", "上传文件类型不符合,必须是以下几种<br/>"
						+ this.allowedUploadFlash.toString());
				return new ModelAndView("admin/common/message", map);
			}
			String fileName = DateFormatUtils.format(new Date(),
					"yyyyMMddHHmmss")
					+ "."
					+ FilenameUtils.getExtension(originalFilename);
			String basePath = request.getRealPath("/") + "/";
			String relativePath = "userfiles/upload/flash/"
					+ DateFormatUtils.format(new Date(), "yyyy-MM-dd")
							.replaceAll("-", "/") + "/";
			FileUtils.mkdirs(basePath + relativePath);
			multipartFile.transferTo(new File(basePath + relativePath
					+ fileName));
			flashInfo.setFlashPath(relativePath + fileName);
		}

		if (this.flashInfoDao.udpateFlash(flashInfo))
			message = "栏目Flash修改成功!";
		else {
			message = "栏目Flash修改失败!";
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}

	@RequestMapping({ "/list" })
	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws Exception {
		ModelAndView mav = new ModelAndView("admin/flashInfo/flashInfoList");

		List<ChannelInfo> channelInfoList = this.channelInfoDao
				.getSubListByParentIdLanguageId(0, 0, 0, 2147483647);
		List<LanguageInfo> languageInfoList = this.languageInfoDao.getAll();
		Map<Integer,String> channelMap = this.channelInfoDao.getAllChannelAsMap();
		Map<Integer,String> languageMap = this.languageInfoDao.getLanuageMap();

		int languageId = StringUtils.isNotBlank(request
				.getParameter("languageId")) ? Integer.parseInt(request
				.getParameter("languageId")) : 1;
		int channelId = StringUtils.isNotBlank(request
				.getParameter("channelId")) ? Integer.parseInt(request
				.getParameter("channelId")) : 0;

		int curPage = StringUtils.isNotBlank(request.getParameter("curPage")) ? Integer
				.parseInt(request.getParameter("curPage")) : 1;
		PageBean pageBean = new PageBean();
		pageBean.setCurPage(curPage);
		List<FlashInfo> flashInfoList = this.flashInfoDao.getSubList(languageId,
				channelId, pageBean.getStart(), pageBean.getRowsPerPage());
		pageBean.setMaxRowCount(this.flashInfoDao.getCount(languageId,
				channelId));
		pageBean.setMaxPage();
		pageBean.setPageNoList();

		map.put("channelInfoList", channelInfoList);
		map.put("languageInfoList", languageInfoList);
		map.put("channelMap", channelMap);
		map.put("languageMap", languageMap);
		map.put("flashInfoList", flashInfoList);
		map.put("pageBean", pageBean);
		map.put("languageId", Integer.valueOf(languageId));
		map.put("channelId", Integer.valueOf(channelId));
		mav.addAllObjects(map);
		return mav;
	}

	@RequestMapping({ "/delete" })
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/common/message");
		String message = "";
		int flashId = StringUtils.isNotBlank(request.getParameter("flashId")) ? Integer
				.parseInt(request.getParameter("flashId")) : 0;
		if (this.flashInfoDao.deleteFlash(flashId))
			message = "栏目Flash删除成功!";
		else {
			message = "栏目Flash删除失败!";
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}

	public boolean isAllowed(String fileName) {
		for (String suffix : this.allowedUploadFlash) {
			if (StringUtils.equalsIgnoreCase(suffix,
					FilenameUtils.getExtension(fileName))) {
				return true;
			}
		}
		return false;
	}
}